package com.cgbl.cg.view;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.lang.ref.WeakReference;

/**
 * Created by Eric.Gao on 2016/12/28.
 */

public class CustomWebClient extends WebViewClient {
    private WeakReference<WebClientCallback> mCallbackRef;

    public CustomWebClient(WebClientCallback callback) {
        mCallbackRef = new WeakReference<>(callback);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        WebClientCallback callback = mCallbackRef.get();
        if (callback != null) {
            return callback.shouldOverrideUrlLoading(view, url);
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        WebClientCallback callback = mCallbackRef.get();
        if (callback != null) {
            callback.onLoadResource(view, url);
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        WebClientCallback callback = mCallbackRef.get();
        if (callback != null) {
            callback.onPageFinished(view, url);
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        WebClientCallback callback = mCallbackRef.get();
        if (callback != null) {
            callback.onPageStarted(view, url, favicon);
        }
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        WebClientCallback callback = mCallbackRef.get();
        if (callback != null) {
            callback.onReceivedSslError(view, handler, error);
        }
    }

    public interface WebClientCallback {
        boolean shouldOverrideUrlLoading(WebView view, String url);

        void onLoadResource(WebView view, String url);

        void onPageFinished(WebView view, String url);

        void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error);

        void onPageStarted(WebView view, String url, Bitmap favicon);
    }

}
